package com.itheima.stargraph.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.itheima.stargraph.utils.JWTUtils;
import com.itheima.stargraph.utils.UserThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * TODO
 *
 * @Author huang
 * @Date 2025/6/11 2025/6/11
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是不是controller方法
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取请求头的token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        //判断token是否为空
        if (StrUtil.isBlank(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        //解析token
        boolean result = JWTUtils.verify(token);
        //5. 若果解析失败，则响应401
        if(!result) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        //6. 设置用户信息到ThreadLocal
        UserThreadLocalUtils.setUser(JWTUtils.getUser(token));

        //7. 放行请求
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.removeUser();
    }
}
